package com.ysu.zyw.service;

import com.ysu.zyw.dao.BlogMessageMapper;
import com.ysu.zyw.dao.BlogUserMapper;
import com.ysu.zyw.modal.dto.BlogLeavingMessageInformation;
import com.ysu.zyw.modal.po.BlogMessageEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;

/**
 * Created by zhang_yao_wu1993 on 15/4/25.
 *
 * @author by Zerur
 */
@Service("blogMessageService")
public class BlogMessageService {
    private BlogUserMapper blogUserMapper;
    private BlogMessageMapper blogMessageMapper;

    public BlogUserMapper getBlogUserMapper() {
        return blogUserMapper;
    }

    @SuppressWarnings("all")
    @Resource
    public void setBlogUserMapper(BlogUserMapper blogUserMapper) {
        this.blogUserMapper = blogUserMapper;
    }

    public BlogMessageMapper getBlogMessageMapper() {
        return blogMessageMapper;
    }

    @SuppressWarnings("all")
    @Resource
    public void setBlogMessageMapper(BlogMessageMapper blogMessageMapper) {
        this.blogMessageMapper = blogMessageMapper;
    }


    @Transactional
    @RolesAllowed("ROLE_USER")
    public void leavingMessage(BlogLeavingMessageInformation blogLeavingMessageInformation) {
        // 获得当前用户 id
        Integer currentUserId = this.getCurrentUserId();

        // 构造实体
        BlogMessageEntity blogMessageEntity = new BlogMessageEntity(blogLeavingMessageInformation, currentUserId);

        // 插入留言
        blogMessageMapper.insertBlogMessageEntity(blogMessageEntity);
    }

    private Integer getCurrentUserId() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Integer currentUserId = blogUserMapper.selectIdByUsername(username);
        return currentUserId;
    }
}
